package com.xiaoma.common.observer.single

import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.xiaoma.common.extend.runOnMainThread
import com.xiaoma.common.observer.Observer
import java.util.concurrent.ConcurrentHashMap

/**
 * author: liangjingbo
 * date: 2022/7/1
 * describe: 单数据观察者，只能收到最后一次发送的数据
 */
class SingleDataObserverWrapper<T>(
    private val owner: LifecycleOwner,
    val observer: Observer<T>,
    private val isCurResumeReceived: Boolean,
    private val mWrappers: ConcurrentHashMap<Observer<T>, SingleDataObserverWrapper<T>>
) : LifecycleEventObserver {


    companion object {
        const val TAG = "EventDataObserverWrapperTag"
        const val START_VERSION = -1
    }


    private var mData: T? = null

    private var mVersion = START_VERSION

    private var mLastVersion = START_VERSION


    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        val currentState = owner.lifecycle.currentState
        if (currentState == Lifecycle.State.DESTROYED) {
            mWrappers.remove(observer)
            owner.lifecycle.removeObserver(this)
            return
        }
        if (currentState != Lifecycle.State.RESUMED) {
            return
        }
        if (mLastVersion >= mVersion) {
            Log.w(TAG, "onStateChanged() state: $currentState" +
                    ", mLastVersion >= mVersion mLastVersion: $mLastVersion ,mVersion: $mVersion")
            return
        }
        mLastVersion = mVersion
        mData?.let {
            observer.onChange(it)
        }
    }

    fun setData(value: T) {
        mVersion++
        mData = value
        val currentState = owner.lifecycle.currentState
        if (currentState != Lifecycle.State.RESUMED) return
        mLastVersion = mVersion
        if (!isCurResumeReceived) return
        runOnMainThread {
            mData?.let {
                observer.onChange(it)
            }
        }
    }

}